﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Xml.Serialization;
using Microsoft.Win32;
using Startup.Base.Utils;
using Startup.Project.Algorithm;
using Startup.Project.Classes;

namespace Startup.Shell.Domain.FunctionalityContracts
{
	public class SaveCommandContract : CommandContractBase
	{
		public override string CommandName
		{
			get { return "Save"; }
		}

		public override AlgorithmAction[] GetContent(ClassBase dataContextType, StartupProperty property)
		{
			CreateAction createWindow = new CreateAction(new ConstructorDefinition(new StandartClass(typeof(SaveFileDialog))));
			CallMethodAction showWindow = new CallMethodAction(createWindow.Result, new MethodDefinition(new StandartClass("bool?", "System"), "ShowDialog", new MethodParameter("owner", new StandartClass(typeof(Window)))), new Field("App.Current.MainWindow", new StandartClass(typeof(Window)), false, false));
			CustomAction checkResult = new CustomAction("if (!{0}.Value) return;", showWindow.Result);
			CreateAction createSerializer = new CreateAction(new ConstructorDefinition(new StandartClass(typeof(XmlSerializer)), new MethodParameter("type", new StandartClass(typeof(Type)))), new Field(string.Format("typeof({0})", dataContextType.Name), new StandartClass(typeof(Type)), false, false));

			CustomAction openStream = new CustomAction("using (System.IO.FileStream stream = System.IO.File.Create({0}.FileName))", createWindow.Result);
			CustomAction saveProperty = new CustomAction(string.Format("{1}.Serialize(stream, {0});", property.Name, "{0}"), createSerializer.Result);

			List<AlgorithmAction> scenario = new List<AlgorithmAction>();
			scenario.Add(createWindow);
			scenario.Add(showWindow);
			scenario.Add(checkResult);
			scenario.Add(createSerializer);
			scenario.Add(openStream);
			scenario.Add(saveProperty);

			return scenario.ToArray();
		}
	}
}
